<?php

declare(strict_types=1);

namespace Service\MnGoodsService;

use App\Model\BbcModel\Goods;
use App\Model\BbcModel\GoodsClass;
use App\Model\BbcModel\MnStoreGoods;
use App\Model\BbcModel\Mnuser;
use MathPHP\Probability\Distribution\Continuous\F;
use PhpParser\Node\Stmt\Nop;
use Service\BaseService;
use Service\Code\Normal;
use Service\GoodsService\GoodsClassService;

class MnGoodsService extends BaseService
{
    /**
     * 单独获取分类
     * @param int $pid
     * @return array
     */
    public function getClass(int $pid = 0)
    {
        $goodsClass = GoodsClassService::instance()->getClass(['pid' => $pid]);
        $classIds = Goods::instance()->where('df', 0)->where('status', 1)->pluck('class_id');
        $goodsClassData = $this->getClassTree($goodsClass, $classIds);
        return Normal::returnCode(Normal::SUC, '请求成功', $goodsClassData);
    }

    /**
     * 跨境Q店分类
     * @param int $mnid
     * @param int $mn_sid
     * @return array
     */
    public function getGlobalClass(int $mnid, int $mn_sid): array
    {
        $goodsClass = GoodsClassService::instance()->getClass(['pid' => 0]);
        $mnUser = Mnuser::instance()->info(['id' => $mn_sid, 'status' => 1, 'new_store' => 1]);
        $sid = getSID();
        if (empty($mnUser)) {
            return Normal::returnCode(Normal::FAIL, 'q店不存在');
        }
        $classIds = Goods::instance()->from(Goods::instance()->getTable() . ' g')
            ->Leftjoin(MnStoreGoods::instance()->getTable() . ' mg', function ($join) use ($mn_sid) {
                $join->on('mg.goods_id', '=', 'g.id')->on('mg.df', '=', 0)->on('mg.mn_sid', '=', $mn_sid);
            })
            ->where('g.df', 0)
            ->where('g.cid', $mnUser['cid'])
            ->where('g.sid', $sid)
            ->where('mg.status', 1)
            ->where('g.status', 1)
            ->pluck('class_id');
        $goodsClassData = $this->getClassTree($goodsClass, $classIds);
        return Normal::returnCode(Normal::SUC, '请求成功', $goodsClassData);
    }

    private function getClassTree($goodsClass, $classIds)
    {
        $goodsClassData = [];
        foreach ($goodsClass['data'] as $class) {
            $son = [];
            foreach ($class['son'] as $classSon) {
                $grandSon = [];
                foreach ($classSon['son'] as $classGrandSon) {
                    if (in_array($classGrandSon['id'], $classIds)) {
                        $grandSon[] = $classGrandSon;
                    }
                }
                if (in_array($classSon['id'], $classIds) || count($grandSon) > 1) {
                    $son[] = $classGrandSon;
                }
            }
            $class['son'] = $son;
            if (in_array($class['id'], $classIds) || count($son) > 0) {
                $goodsClassData[] = $class;
            }
        }
        return $goodsClassData;
    }
}
